const { getAll, update, add, getOne, getCount, getSum } = require('../utils/dbTools')
const tableName = 'finance'

/**
 * 资金流水列表
 * @param {object} map 查询条件 {bus_id,page,size}
 * 
*/
const getFinanceList = async (map = {}) => {
    const result = await getAll(tableName, { ...map, status: 1 })
    return result
}

/**
 * 添加资金流水记录
 * @param {object} data={bus_id,patient_id,doctor_id,amount,type,pay_way,trade_time}
*/
const addFinanceRecord = async (data) => {
    if (!data) return false
    const row = { ...data}
    const { insertId } = await add(row, tableName)
    return insertId
}

/**
 * 删除资流水记录
 * @param {number} id 记录id 
*/
const removeFinanceRecord = async (id) => {
    if (!data) return false
    // const result = await remove(id, tableName)
    // 逻辑删除
    const result = await update(id, { status: -1 }, tableName)
    return result
}

/**
 * 更新资流水记录
 * @param {number} id 记录id 
 * @param {object} data={} 要更新的字段
*/
const updateFinanceRecord = async (id, data) => {
    if (!data) return false
    const result = await update(id, data, tableName)
    return result
}

/**
 * 查询资金流水记录详情
 * @param {number} id 记录id 
*/
const getFinanceRecord = async (id) => {
    if (!data) return false
    const result = await getOne(tableName, { id })
    return result
}

/**
 * 统计收款和退款总金额
 * @param {object } map={doctor_id,bus_id}
*/
const countFinance = async (map) => {
    if (!map.doctor_id || !map.bus_id) return false
    // 收款
    const income = await getSum(tableName, 'amount', { ...map, type: 1, status: 1 })
    // 退款
    const refund = await getSum(tableName, 'amount', { ...map, type: 2, status: 1 })
    return {
        income, refund
    }
}


module.exports = {
    getFinanceList, addFinanceRecord, removeFinanceRecord, updateFinanceRecord, getFinanceRecord,countFinance
}
